package mshop.com.schild_kotlin.base

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import mshop.com.schild_kotlin.R
import mshop.com.schild_kotlin.events.EventConstant
import mshop.com.schild_kotlin.events.MessageEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Created by mayi on 2018/5/23.
 * @Autor CaiWF
 * @Email 401885064@qq.com
 * @TODO
 */
abstract class BaseFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener {
    var rootView: View? = null
    val ProgressBarTiem: Long = 1000
    var refreshLayout: SwipeRefreshLayout? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutResources(), container, false)
        }
        if (getNeedRefresh()) {
            refreshLayout = rootView?.findViewById(R.id.refreshLayout)
        }
        return rootView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
        initRefreshLayout()
    }

    private fun initRefreshLayout() {
        if (getNeedRefresh() && refreshLayout != null && !refreshLayout!!.isRefreshing) {
            //设置下拉刷新监听
            refreshLayout!!.setOnRefreshListener(this)
            refreshLayout!!.isRefreshing = true
            refreshLayout!!.postDelayed({
                onRefresh()
            }, ProgressBarTiem)
        } else {
            onRefresh()
        }
    }


    /************************EventBus*****************************/
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent) {
        when (event.eventTag) {
            EventConstant.CancelHttpLoading -> {
                if (refreshLayout != null && refreshLayout!!.isRefreshing) {
                    refreshLayout!!.isRefreshing = false
                }
            }
        }
    }

    public override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    public override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }

    abstract fun getLayoutResources(): Int
    abstract fun initView()
    abstract fun getNeedRefresh(): Boolean
}